package com.zuiacsn.forum.service.impl;

import com.zuiacsn.forum.common.AppResult;
import com.zuiacsn.forum.common.ResultCode;
import com.zuiacsn.forum.dao.ArticleMapper;
import com.zuiacsn.forum.exception.ApplicationException;
import com.zuiacsn.forum.model.Article;
import com.zuiacsn.forum.model.Board;
import com.zuiacsn.forum.model.User;
import com.zuiacsn.forum.service.IArticleService;
import com.zuiacsn.forum.service.IBoardService;
import com.zuiacsn.forum.service.IUserService;
import com.zuiacsn.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {


    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    IBoardService boardService;
    @Autowired
    IUserService userService;
    /**
     * 发布帖子
     * @param article 要发布的帖子
     */
    @Override
    public void create(Article article) {
        // 非空校验
        if(article == null || article.getUserId() == null || article.getBoardId() == null
        || StringUtil.isEmpty(article.getTitle()) || StringUtil.isEmpty(article.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 设置默认值
        article.setVisitCount(0);
        article.setReplyCount(0);
        article.setLikeCount(0);
        article.setState((byte) 0);
        article.setDeleteState((byte) 0);
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());

        // 写入数据库
        int row = articleMapper.insert(article);
        if(row <= 0){
            log.warn(ResultCode.FAILED_CREATE.toString()+", 受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        userService.addOneArticleCountById(article.getUserId());
        boardService.addOneArticleCountById(article.getBoardId());
    }


    @Override
    public List<Article> selectAll() {
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        // 非空校验
        if(boardId == null || boardId == 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Board board = boardService.selectById(boardId);
        // 板块不存在
        if(board == null){
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        // 查询并返回
        return articleMapper.selectAllByBoardId(boardId);
    }

    /**
     * 根据传入的帖子id查询帖子详情
     * @param id
     * @return
     */
    @Override
    public Article selectDetailById(Long id) {
        // 非空校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Article article = articleMapper.selectDetailById(id);
        if(article == null){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 更新帖子的访问数量
        Article updateArticle = new Article();
        updateArticle.setVisitCount(article.getVisitCount()+1);
        updateArticle.setId(article.getId());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        // 返回结果
        article.setVisitCount(article.getVisitCount()+1); // 更新返回对象的访问次数
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        // 非空校验
        if(id == null || id <= 0 || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 更新数据库
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public Article selectById(Long id) {
        // 非空校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectByPrimaryKey(id);
    }

    @Override
    public void thumbsUpById(Long id) {
        // 非空校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Article article = articleMapper.selectByPrimaryKey(id);
        // 帖子不存在
        if(article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 帖子状态异常
        if(article.getState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 更新数据库
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount()+1);
        updateArticle.setUpdateTime(new Date());

        int row  = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    /**
     * 删除帖子
     * @param id
     */
    public void deleteById(Long id) {
        // 非空校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Article article = articleMapper.selectByPrimaryKey(id);
        // 帖子不存在
        if(article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        // 更新数据库
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte) 1);
        updateArticle.setUpdateTime(new Date());

        int row  = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        // 更新板块中的帖子数量
        boardService.subOneArticleCountById(article.getBoardId());
        // 更新用户帖子数量
        userService.subOneArticleCountById(article.getUserId());
        log.info("删除帖子成功! article id = "+article.getId()+", userid = "+article.getUserId());
    }

    @Override
    public void addOneReplayCountById(Long id) {
        // 非空校验
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Article article = articleMapper.selectByPrimaryKey(id);
        // 帖子不存在
        if(article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }


        // 更新数据库
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setReplyCount(article.getReplyCount()+1);
        updateArticle.setUpdateTime(new Date());

        int row  = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    /**
     * 根据用户id查询帖子列表
     * @param userId
     * @return
     */
    public List<Article> selectByUserId(Long userId) {
        // 非空校验
        if(userId == null || userId <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        User user = userService.selectById(userId);
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"userid = "+userId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        // 查数据库
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }


}
